<?php

namespace app\models\charge;

use app\models\user\ChargeRules;
use wanyue\basic\BaseModel;
use wanyue\traits\ModelTrait;
use app\models\user\User;
/**
 * TODO 用户充值记录
 */
class Charge extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'charge_user';

    use ModelTrait;
	
	
    public static function createorder($ruleid,$uid,$coin,$money,$type)
    {
		$checkwhere=[];
		$checkwhere[]=[
			'id','=',$ruleid
		];
		$checkwhere[]=[
			'coin','=',$coin
		];
		$checkwhere[]=[
			'money','=',$money
        ];		

		$check=ChargeRules::where($checkwhere)->find()->toArray();
		if(!$check){
			return 1;
        }

		$insert=[
			'uid'=>$uid,
			'touid'=>$uid,
			'money'=>$money,
			'coin'=>$coin,
			'coin_give'=>$check['give'],
			'status'=>0,
			'addtime'=>time(),
			'type'=>$type,
			'orderno'=>self::getNewOrderId(),
        ];
        $order=self::create($insert);

		if(!$order){
			return 1;
		}
		else{
			return $order;
		}
    }
    public static function getNewOrderId()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'wx' . $msectime . mt_rand(10000, 99999);

        if (self::where(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        return $orderId;
    }	
    /**
     * //TODO用户充值成功后
     * @param $orderId
     */
    public static function rechargeSuccess($orderId)
    {
	//	file_put_contents('chargelog/'.date('y-md').'.txt','进入模型：'.$orderId.'时间：'.date('Y-m-d h:i:s')."\r\n",FILE_APPEND);
        $order = self::where('orderno', $orderId)->where('status', 0)->find();
	//	file_put_contents('chargelog/'.date('y-md').'.txt','查询订单：'.json_encode($order).'时间：'.date('Y-m-d h:i:s')."\r\n",FILE_APPEND);
        if (!$order) return false;
        $user = User::getUserInfo($order['touid']);
	//	file_put_contents('chargelog/'.date('y-md').'.txt','查询用户：'.json_encode($user).'时间：'.date('Y-m-d h:i:s')."\r\n",FILE_APPEND);
        self::beginTrans();
        $price = $order['coin']+$order['coin_give'];
        $res1 = self::where('orderno', $orderId)->update(['status' => 1]);
	//	file_put_contents('chargelog/'.date('y-md').'.txt','修改订单：'.json_encode($res1).'时间：'.date('Y-m-d h:i:s')."\r\n",FILE_APPEND);
        $res3 = User::edit(['coin' => $user['coin']+$price], $order['touid'], 'uid');
	//	file_put_contents('chargelog/'.date('y-md').'.txt','修改用户：'.json_encode($res3).'时间：'.date('Y-m-d h:i:s')."\r\n",FILE_APPEND);
        $res = $res1  && $res3;
        self::checkTrans($res);
        event('RechargeSuccess', [$order]);
        return $res;
    }

}